package com.cherry.i18n.service.impl;

import com.cherry.i18n.service.I18nService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Locale;
import java.util.Objects;

/**
 * I18n Service
 *
 * @author sinbad.cheng
 * @since 2022-01-10
 */
@Service
public class I18nServiceImpl implements I18nService {

    private final static Logger LOGGER = LoggerFactory.getLogger(I18nServiceImpl.class);

    private final MessageSource messageSource;

    public I18nServiceImpl(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    @Override
    public String getMessage(String messageCode, Locale locale, String defaultMessage, Object[] args) {
        try {
            String message = messageSource.getMessage(messageCode, args, locale);
            return Objects.equals(message, messageCode) ? defaultMessage : message;
        } catch (Exception e) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[国际化]未找到对应国际化配置，code: {}, locale: {}, args: {}",
                        messageCode, locale, Arrays.toString(args));
            }
        }
        return defaultMessage;
    }

}